import React, { useState, useEffect } from "react";
import "./index.less";
import Header from "@/components/header";
import { Input, Popup, Form, Toast } from "antd-mobile";
import Button, { ButtonGroup } from "@/components/button";
import { useLocalStorageState, useRequest } from "ahooks";
import { LOCAL_APP_INFO } from "@/utils/const";
import closeIcon from "@/assets/images/close.png";
import authIcon from "@/assets/images/auth.png";
import authBtnIcon from "@/assets/images/authBtn.jpg";
import { useNavigate } from "react-router-dom";
import { realNameAuthentication, getCanQrCode } from "@/api/authentication";
import CustomModal from "../../components/customModal";

const onSetAuth = () => {
  const style = { position: "relative", top: 3, right: 0 };
  return (
    <img src={authBtnIcon} style={style} alt="确认" width={16} height={16} />
  );
};

function Auth() {
  const navigate = useNavigate();
  const [visible, setVisible] = useState(true);
  const [successVisible, setSuccessVisible] = useState(false);
  const [form] = Form.useForm();
  const [appInfoData] = useLocalStorageState(LOCAL_APP_INFO);
  const { run, cancel } = useRequest(getCanQrCode, {
    manual: true,
    pollingInterval: 2000,
    pollingErrorRetryCount: 60,
    onSuccess: (res) => {
      if (res?.data) {
        setVisible(false);
        setSuccessVisible(false);
        cancel();
        navigate("/paycode", { replace: true });
        form.resetFields();
      } else {
        setSuccessVisible(true);
      }
    },
  });

  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
    window.history.back();
    setSuccessVisible(false);
  };

  const handleConfirm = async () => {
    const values = await form.validateFields();
    realNameAuthentication(values).then((res) => {
      run();
    });
  };

  useEffect(() => {
    return () => {
      setVisible(false);
      form.resetFields();
      setSuccessVisible(false);
      cancel();
    };
  }, [appInfoData]);

  return (
    <div className="authentication-page">
      <Header />
      <div className="authentication-content">
        <Popup
          visible={visible}
          onMaskClick={handleCancel}
          position="bottom"
          bodyStyle={{
            padding: "24px",
            borderTopLeftRadius: "12px",
            borderTopRightRadius: "12px",
          }}
        >
          {/* 标题栏 */}
          <div className="popup-header">
            <h2 className="popup-title">实名认证</h2>
            <div className="popup-close" onClick={handleCancel}>
              <img src={closeIcon} alt="关闭" width={18} height={18} />
            </div>
          </div>
          <Form
            form={form}
            layout="horizontal"
            initialValues={{
              phone: appInfoData?.phone,
            }}
          >
            <Form.Item
              className="form-item-phone"
              name="phone"
              label="手机号码"
              rules={[{ required: true, message: "手机号码不能为空" }]}
            >
              <Input placeholder="手机号码" readOnly />
            </Form.Item>
            <Form.Item
              className="form-item-name"
              name="name"
              label="真实姓名"
              rules={[
                { required: true, message: "请输入真实姓名" },
                {
                  validator: (_, v) => {
                    if (!v) return Promise.resolve();
                    return /^[\u4e00-\u9fa5·]{2,}$/u.test(v)
                      ? Promise.resolve()
                      : Promise.reject("仅限中文，至少2个字符");
                  },
                },
              ]}
            >
              <Input placeholder="输入真实姓名" clearable />
            </Form.Item>
            <Form.Item
              className="form-item-id"
              name="certifId"
              label="身份证号"
              rules={[
                { required: true, message: "请输入身份证号" },
                {
                  pattern:
                    /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                  message: "请输入正确的身份证号",
                },
              ]}
            >
              <Input placeholder="输入身份证号" />
            </Form.Item>
          </Form>

          {/* 说明文字 */}
          <div className="auth-explanation">
            <div className="explanation-header">
              <span className="explanation-icon">
                <img src={authIcon} width={16} height={16} />
              </span>
              <span className="explanation-title">实名认证说明</span>
            </div>
            <p className="explanation-text">
              由银联商务提供服务,需要你提供同一手机号相关真实姓名与身份证信息进行核验。
            </p>
          </div>

          {/* 提示文字 */}
          <div className="auth-tip">请查验信息无误后点击确认</div>

          {/* 操作按钮 */}
          <div className="auth-actions">
            <ButtonGroup gap={15} direction="row" equal>
              <Button type="default" block onClick={handleCancel}>
                取消
              </Button>
              <Button
                type="primary"
                block
                icon={onSetAuth()}
                onClick={handleConfirm}
              >
                确认
              </Button>
            </ButtonGroup>
          </div>
        </Popup>

        <CustomModal
          visible={successVisible}
          position={"center"}
          mode={"confirm"}
          title="实名认证成功"
          message="请稍等，正在为您跳转亮码页面..."
          footer={false}
        />
      </div>
    </div>
  );
}

export default Auth;
